package com.idata.service.services;

import com.idata.common.constant.RedisKeyConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

@Service
@Slf4j
public class SearchHistoryService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    private static final int CAPACITY = 6;

    public void addHistory(String identify, String searchContext) {
        String redisKey = formatRedisKey(identify);
        redisTemplate.opsForList().rightPush(redisKey, searchContext);
        trim(redisKey, CAPACITY);
    }

    public List<String> getHistories(String identify) {
        String redisKey = formatRedisKey(identify);
        return redisTemplate.opsForList().range(redisKey, 0, -1);
    }


    private void trim(String redisKey, int capacity) {
        while (Optional.ofNullable(redisTemplate.opsForList().size(redisKey)).orElse(0L) > capacity) {
            redisTemplate.opsForList().leftPop(redisKey);
        }
    }

    private static String formatRedisKey(String identify) {
        return String.format(RedisKeyConstant.SEARCH_HISTORY, identify);
    }
}
